const audioMap = new Map();
const audioEle = new Audio();
function playAudio(path) {
  if (!path) return;
  return new Promise((resolve, reject) => {
    if (audioMap.has(path)) resolve(audioMap.get(path));
    return window.electronAPI.readFile(path).then(data => {
      const str = window.atob(data);
      const u8Arr = new Uint8Array(str.length);
      for (let i = 0; i < str.length; i++) {
        u8Arr[i] = str.charCodeAt(i);
      }
      const blob = new Blob([u8Arr], { type: "audio/mpeg" });
      const url = URL.createObjectURL(blob);
      resolve(url);
    });
  }).then((url: any) => {
    audioEle.pause();
    audioEle.currentTime = 0;
    audioEle.src = url;
    audioEle.play();
    audioMap.set(path, url);
    return new Promise((resolve, reject) => {
      audioEle.addEventListener("ended", event => {
        resolve("ended");
      });
    });
  });
}

export { playAudio };
